package com.atguigu.gulimall.third.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.RRException;
import com.atguigu.gulimall.third.utils.ConstantSmsUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.atguigu.gulimall.third.service.SmsService;

import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {

    /**
     * 发送短信
     */
    public boolean send(String PhoneNumbers, String templateCode, Map<String, Object> param) {

        if (StringUtils.isEmpty(PhoneNumbers)) return false;

        DefaultProfile profile =
                DefaultProfile.getProfile("default", ConstantSmsUtils.ACCESS_KEY_ID, ConstantSmsUtils.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);
        request.putQueryParameter("SignName", "华丽逸尚");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(JSON.toJSONString(response));
//            if(response.getHttpResponse().getHttpContentString().ge)
            System.out.println(JSON.toJSONString(response));
            if(response.getHttpResponse().isSuccess()){
                Map parse = JSONObject.parseObject(response.getData());
                if (!parse.get("Message").equals("OK")){
                    throw new RRException(BizCodeEnum.UNKNOWN_EXCEPTION.getMsg(),BizCodeEnum.UNKNOWN_EXCEPTION.getCode());
                }

            }
            return true;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
